<!--
 * @Author: Rachel 943701297@qq.com
 * @Date: 2022-07-13 16:36:55
 * @LastEditors: Rachel 943701297@qq.com
 * @LastEditTime: 2022-07-14 09:22:40
 * @FilePath: \JS\java-script-learning-notes\JSCode\键盘事件.html
 * @Description: 
 * 
 * Copyright (c) 2022 by Rachel 943701297@qq.com, All Rights Reserved. 
-->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Keyborad Events</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      #box1 {
        width: 502px;
        height: 402px;
        border: 2px solid black;
      }
      #box {
        position: absolute;
        width: 50px;
        height: 50px;
        padding: 2px 0 0 2px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div id="box1">
      <div id="box"></div>
    </div>
    <!-- <input type="text" />
    <button id="btn">reload</button> -->
  </body>
  <script>
    /*  let input = document.getElementsByTagName("input")[0];
    input.onkeydown = (e) => {
      console.log("输入框输入" + e.keyCode);
      let reg = /[0-9]/;
      if (reg.test(e.key)) {
        //在文本框中输入内容，属于onkeydown的默认行为
        //如果在onkeydown中取消了默认行为，则输入的内容，不会出现在文本框中
        return false;
      }
    }; */

    /* let btn = document.getElementById("btn");
    btn.onclick = (e) => {
      location.reload(true);
    }; */

    let box = document.getElementById("box");
    let h = parseInt(window.getComputedStyle(box, null)["height"].slice(0, -2));
    let w = parseInt(window.getComputedStyle(box, null)["width"].slice(0, -2));
    let box1 = document.getElementById("box1");
    let h1 = parseInt(
      window.getComputedStyle(box1, null)["height"].slice(0, -2)
    );
    let w1 = parseInt(
      window.getComputedStyle(box1, null)["width"].slice(0, -2)
    );
    let speed = 10;
    let dir = "";
    let timer = setInterval(() => {
      switch (dir) {
        case "ArrowDown":
          // console.log(box.offsetTop + " " + h + " " + h1);
          if (box.offsetTop + h < h1) {
            box.style.top = box.offsetTop + speed + "px";
          }
          break;
        case "ArrowUp":
          // console.log(box.offsetTop + " " + h + " " + h1);
          if (box.offsetTop > 2) {
            box.style.top = box.offsetTop - speed + "px";
          }
          break;
        case "ArrowRight":
          if (box.offsetLeft + w < w1) {
            box.style.left = box.offsetLeft + speed + "px";
          }
          break;
        case "ArrowLeft":
          if (box.offsetLeft > 2) {
            box.style.left = box.offsetLeft - speed + "px";
          }
          break;
      }
    }, 10);
    document.onkeydown = (e) => {
      if (e.ctrlKey) {
        speed = 100;
      } else {
        speed = 10;
      }
      dir = e.key;
    };
    document.onkeyup = (e) => {
      dir = "";
    };
  </script>
</html>
